$(function () {
    //*************************************************

    initPage();// 初始化页面 --ok
    setChangePage( getItemList );// 页码切换 --ok
    /********************************************/
    // 初始化页面 --ok
    function initPage() {
        let itemType_header = [],
            itemType_son = [];

        let getCollege = new Promise( ( resolve, reject)=>{
            $.ajax({
                url : '/institute/list.do',
                type : 'post',
                data : {},
                dataType : 'json',
                xhrFields : {
                    withCredentials: true
                },
                crossDomain: true,
                success : function (data){
                    if(data.status == 0){
                        resolve(data);
                    }else if(data.status == 10){
                        reject(data);
                    }else{
                        reject(data);
                    }
                },
                error : function (data){
                    reject(data);
                }
            })
        } );
        let getItemType = new Promise( (resolve, reject)=> {
            // 获取所有申报类型
            $.ajax({
                url : '/manage/racetype/get_raceType.do',
                type:'post',
                data : {parentId:0},
                dataType : 'json',
                ContentType : 'application/x-www-form-urlencoded',
                withCredential : true ,
                xhrFields : {
                    withCredentials: true
                },
                crossDomain: true,
                success: function (data) {
                    if(data.status == 0){
                        resolve( data );
                    }else if(data.status ==10){
                        reject(data);
                    }else{
                        reject(data);
                    }
                },
                error : function(data){
                    reject(data);
                }
            });
        } );
        let initSelect = Promise.all( [getCollege, getItemType] );

        initSelect.then( (data)=>{

            let college = data[0].data;// 学院
                itemType_header = data[1].data;// itemType

            // 学院
            let college_Box = $('#college-Sele');
            college_Box.html('');
            college_Box.prepend($('<option value="">全部学院</option>'));
            for( let i=0; i<college.length; i++ ){
                let DOM = $('<option value="'+ college[i].stuinstitutename +'">'+ college[i].stuinstitutename +'</option>');
                college_Box.append( DOM );
            }

            // item类型
            getSonType( itemType_header );
        }).catch((data)=>{
            if(data.status == 10){
                spop_er(data.msg,function () {},outLogin);
            }
        });

        // 获取子项目类型 --ok
        function getSonType( itemType_header ) {
            console.log(itemType_header);
            for( let i=0; i<itemType_header.length; i++ ){
                // 获取每个子项目类型
                itemType_son[i] = new Promise((resolve, reject) => {
                    $.ajax({
                        url : '/manage/racetype/get_raceType.do',
                        type:'post',
                        data : {
                            parentId : itemType_header[i].racetypeno
                        },
                        dataType : 'json',
                        ContentType : 'application/x-www-form-urlencoded',
                        withCredential : true ,
                        xhrFields : {
                            withCredentials: true
                        },
                        crossDomain: true,
                        success: function (data) {
                            if(data.status == 0){
                                resolve( data );
                            }else if( data.status == 10 ){
                                reject( data );
                            }
                        },
                        error : function (data) {
                            reject( data );
                        }
                    });
                });
            }

            let itemSon = Promise.all( itemType_son );

            itemSon.then( (data)=>{
                To_ItemType(data);
            }).catch( (data)=>{
                if( data.status == 10 ){
                    spop_waring( data.msg, function () {}, outLogin )
                }
            } );
        }
        // 渲染子项目类型 ==> 获取项目列表 --ok
        function To_ItemType(data) {
            let projecttype_Box = $('#projecttype-Sele');
            projecttype_Box.html('');
            projecttype_Box.append( $('<option value="">全部项目类型</option>') );

            // 头
            for(let i=0; i<itemType_header.length; i++){
                let selectDOM = $('<optgroup label="'+ itemType_header[i].racetype +'"></optgroup>');

                // son
                for(let j=0; j<data[i].data.length; j++){
                    let info = data[i].data;
                    let optionDOM = $('<option value="'+ info[j].racetype +'">'+ info[j].racetype +'</option>');
                    selectDOM.append( optionDOM );
                }
                projecttype_Box.append( selectDOM );
            }

            // 获取项目列表
            getItemList();
        }
    }

    // 获取项目列表 -ok
    function getItemList() {
        $.ajax({
            url: '/manage/projectDetails/list_product.do',
            type: 'post',
            data: {
                pageNum : oPageInfo.pageNum,
                pageSize : oPageInfo.pageSize,
                name : oPageInfo.searchInfo,
                startTime : oPageInfo.startTime,
                stopTime : oPageInfo.stopTime,

                projectType : oPageInfo.projectType,
                stuInstitute : oPageInfo.stuInstitute,
                examineStatus : oPageInfo.examineStatus
            },
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success: function (data) {
                if (data.status == 0) {
                    // 渲染项目列表
                    let itemObj = data.data;
                    To_ItemList( itemObj    ) ;
                }else if( data.status == 10 ){
                    spop_waring( data.msg, function () {}, outLogin )
                }else{
                    spop_er( data.msg );
                }
            }
        });
    }
    // 渲染页面 --ok
    function To_ItemList( oData ){
        let tabelBox = $('#itemTable').find('tbody');
        tabelBox.html('');

        let aData = oData.list;
        aData.forEach( (item,idx)=>{
            let DOM = $('<tr data-id="'+ item.projectno +'" data-youxiu_status="'+ item.youxiu_status +'">' +
                            '<td class="CheckedBox" style="padding-left: 15px ;padding-bottom: 0 ">' +
                                '<input type="checkbox">' +
                            '</td>' +
                            '<td class="itemStatusIcon">' +
                            '   <i class="glyphicon Text-fwb"></i>' +
                            '</td>' +
                            '<td>'+ item.creattime +'</td>' +
                            '<td><a href="/Admin/item-info.html?projectno='+ item.projectno +'">'+ item.projectname +'</a></td>' +
                            '<td class="setThisSele">' +
                            // '<select class="form-control selectActive" name="" >' +
                            //     '<option value="0">未审核</option>' +
                            //     '<option value="1">已通过</option>' +
                            //     '<option value="2">未通过</option>' +
                            // '</select>' +
                            '</td>\n' +
                            '<td>'+ item.instructor +'</td>\n' +
                            '<td>'+ item.projectgrade +'</td>\n' +
                            '<td>'+ item.projecttype +'</td>\n' +
                            '<td>'+ item.stuinstitute +'</td>\n' +
                            '<td class="thisTurnNum"></td>\n' +
                            '<td class="setThisBtn">' +
                            '   <i class="Text-fwb hoverScale Text-cup glyphicon glyphicon-fire"></i>' +
                            // '   <i class="Text-fwb hoverScale Text-cup glyphicon glyphicon-tasks"></i>' +
                            '   <i class="Text-fwb hoverScale Text-cup glyphicon glyphicon-trash"></i>' +
                            '</td>' +
                        '</tr>');
            // 评审状态样式
            DOM = setIconStatus( DOM, item.examinestatus);
            DOM = setItemYouXiu( DOM, item.youxiu_status );
            DOM = setTurnNum( DOM, item.racetypedetailsstate);
            tabelBox.append( DOM );
        } );

        oPageInfo.pages = oData.pages;
        oPageInfo.pageNum = oData.pageNum;
        oPageInfo.pageSize = oData.pageSize;
        oPageInfo.pageTotal = oData.pageTotal;

        setPageFooter();
    }
    // 设置评审状态 and 图标 -ok
    function setIconStatus( DOM_tr, statusCode ) {
        switch ( statusCode ){
            case 0 :
                DOM_tr.find( '.setThisSele' ).html('未审核');
                DOM_tr.find('.itemStatusIcon').children('i').removeClass('glyphicon-ok-sign').removeClass('glyphicon-remove-sign');
                DOM_tr.find('.itemStatusIcon').addClass('active-0').removeClass('active-1').removeClass('active-2');
                DOM_tr.find('.itemStatusIcon').addClass('active-0').children('i').addClass('glyphicon-info-sign');
                break;
            case 1 :
                DOM_tr.find( '.setThisSele' ).html('已通过');
                DOM_tr.find('.itemStatusIcon').children('i').removeClass('glyphicon-info-sign').removeClass('glyphicon-remove-sign');
                DOM_tr.find('.itemStatusIcon').addClass('active-1').removeClass('active-2').removeClass('active-0');
                DOM_tr.find('.itemStatusIcon').addClass('active-1').children('i').addClass('glyphicon-ok-sign');
                break;
            case 2 :
                DOM_tr.find( '.setThisSele' ).html('未通过');
                DOM_tr.find('.itemStatusIcon').children('i').removeClass('glyphicon-info-sign').removeClass('glyphicon-ok-sign');
                DOM_tr.find('.itemStatusIcon').addClass('active-2').removeClass('active-1').removeClass('active-0');
                DOM_tr.find('.itemStatusIcon').addClass('active-2').children('i').addClass('glyphicon-remove-sign');
                break;
        }
        return DOM_tr;
    }
    // 设置优秀项目--ok
    function setItemYouXiu( DOM_tr, statusCode ) {
        switch (statusCode){
            case 1:
                DOM_tr.find('.setThisBtn').find('i').first().addClass('active');
        }
        return DOM_tr;
    }
    // 设置轮次
    function setTurnNum(DOM_Tr, statusCode) {
        let DOM = DOM_Tr.find(".thisTurnNum");
        switch (statusCode){
            case -1 :
                DOM.html('已结束');
                break;
            case 0 :
                DOM.html('未开始');
                break;
            default :
                DOM.html('第'+ statusCode +'轮');
                break;
        }
        return DOM_Tr;
    }

    // 条件筛选
    $('#college-Sele').on('change',function () {
        oPageInfo.stuInstitute = $(this).val();

        getItemList();
    });
    $('#projecttype-Sele').on('change',function () {
        oPageInfo.projectType = $(this).val();
        getItemList();
    });
    $('#examineStatus-Sele').on('change',function () {
        oPageInfo.examineStatus = $(this).val();
        getItemList();
    });
    $('#startDate').on('change',function () {
        oPageInfo.startTime = $(this).val();
        getItemList();
    });
    $('#stopTime').on('change',function () {
        oPageInfo.stopTime = $(this).val();
        getItemList();
    });
    $('#searchInput').on('change',function () {}).keyup(function (ev) {
        switch (ev.keyCode){
            case 13 :
                oPageInfo.searchInfo = $(this).val().trim();
                getItemList();
                break;
            default :
                break;
        }
    });

////////////////////////////////////////////////////////////////////////////

    // 项目审核
    $('#itemReview-btn').on('click',function () {
        let activeItem = checked_TRUE();

        if( activeItem.thisID.length ){
            let status = $('#itemReview-sele').val();
            $.ajax({
                url : '/manage/projectdetailsraceTypesamsara/examine.do',
                type:'post',
                data : {
                    projectnoList : activeItem.thisID,
                    examinestatus : status,// 0,1,2
                    // examineresult : 'aaa',
                    // reviewnotes : '分数'
                },
                xhrFields : {
                    withCredentials: true
                },
                crossDomain: true,
                success: function (data) {
                    if( data.status == 0 ){
                        spop_ok( data.msg, reviewStyle( activeItem.thisDOM, status), off(false) );
                    }else if( data.status == 10 ){
                        spop_waring( data.msg, function () {}, outLogin )
                    }else{
                        spop_waring( data.msg );
                    }
                }
            });
        }else{
            spop_waring('请选中操作');
        }
    });
    /*
    $('#userTable-body').on('change','.selectActive',function () {
        let ID = $(this).parents('tr').attr('data-id');
        let status = $(this).val();

        let aDOM = [];
        aDOM.push( $(this).parents('tr') );

        $.ajax({
            url : '/manage/projectDetails/examine.do',
            type:'post',
            data : {
                projectnoList : ID,
                examinestatus : status,
                examineresult : ''
            },
            xhrFields : {
                withCredentials: true
            },
            crossDomain: true,
            success: function (data) {
                if( data.status == 0 ){
                    spop_ok( data.data, reviewStyle( aDOM, status), off(false) );
                }else if( data.status == 10 ){
                    spop_waring( data.msg, function () {}, outLogin )
                }else{
                    spop_waring( data.msg );
                }
            }
        });
    });
    */
    // 项目评分
    $('#itemCorrect-btn').on('click',function () {
        let activeItem = checked_TRUE();
        let correctVal = $('#itemCorrect-Input').val();

        if( activeItem && (0<= correctVal && correctVal <= 100 && correctVal !== '') ){
            $.ajax({
                url : '/manage/projectdetailsraceTypesamsara/review.do',
                type:'post',
                data : {
                    projectnoList : activeItem.thisID,
                    reviewnotes : correctVal
                },
                ContentType: 'application/x-www-form-urlencoded',
                xhrFields : {
                    withCredentials: true
                },
                crossDomain: true,
                success: function (data) {
                    if( data.status == 0 ){
                        spop_ok( data.msg, getItemList );
                    }else if( data.status == 10 ){
                        spop_waring( data.msg, function () {}, outLogin )
                    }else{
                        spop_waring( data.msg );
                    }
                }
            });
        }else if( !activeItem ){
            spop_waring('请选中项目后操作');
        }else if( 0 > correctVal || correctVal > 100 || correctVal === '' ){
            spop_waring('请输入有效分数',function () {
                $('#itemCorrect-Input').val('');
            });
        }


    });
    // 审核样式
    function reviewStyle( aDOM, status) {
        let addClass = '';

        switch ( Number(status) ){
            case 0 :
                addClass = 'glyphicon glyphicon-info-sign status-0';
                break;
            case 1 :
                addClass = 'glyphicon glyphicon-ok-circle status-1';
                break;
            case 2 :
                addClass = 'glyphicon glyphicon-remove-circle status-2';
                break;
        }
        aDOM.forEach(function (item,idx) {
            item.find('td').eq(1).children('i').removeClass().addClass(addClass);
            item.find( '.selectActive' ).val( status );
        })
    }
////////////////////////////////////////////////////////////////////////////

    // 删除项目  -- ok
    $('#table-tbody').on('click','.glyphicon.glyphicon-trash',function () {

        let activeID = $(this).parents('tr').attr('data-id');
        let itemName = $(this).parents('tr').find('a').html();

        if( confirm("确认删除--《"+ itemName +"》项目") ) {
            $.ajax({
                url: '/manage/projectDetails/delete.do',
                type: 'post',
                data: {
                    projectnoList: activeID
                },
                dataType: 'json',
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                success: function (data) {
                    if (data.status == 0) {
                        spop_ok(data.msg, getItemList);
                    } else if (data.status == 10) {
                        spop_waring( data.msg, function () {}, outLoing );
                    } else {
                        spop_waring();
                    }
                }
            });
        }
    });

    // 设置优秀项目  -- ok
    $('#table-tbody').on('click', '.glyphicon.glyphicon-fire', function () {
        let DOM = $(this).parents('tr');
        let ID =  DOM.attr('data-id');
        let Type = DOM.attr('data-youxiu_status');

        if( Boolean(Number( Type )) ){
            removeYouXiu( ID, DOM );
        }else{
            addYouXiu( ID, DOM );
        }

    });

    // 审核切换
    // $('#table-tbody').on('change', '.selectActive', function () {
    //     console.log($(this).val());
    //     let that = $(this);
    //     let DOM = that.parents('tr');
    //     let domID = DOM.attr('data-id');
    //     $.ajax({
    //         url : '/manage/projectdetailsraceTypesamsara/examine.do',
    //         type:'post',
    //         data : {
    //             projectnoList : [domID],
    //             examinestatus : that.val(),// 0,1,2
    //             // examineresult : 'aaa',
    //             // reviewnotes : '分数'
    //         },
    //         xhrFields : {
    //             withCredentials: true
    //         },
    //         crossDomain: true,
    //         success: function (data) {
    //             if( data.status == 0 ){
    //                 spop_ok( data.msg, ()=>{
    //                     reviewStyle( [DOM], status);
    //                 }, off(false) );
    //             }else if( data.status == 10 ){
    //                 spop_waring( data.msg, function () {}, outLogin )
    //             }else{
    //                 spop_waring( data.msg,function () {
    //                 } );
    //             }
    //         }
    //     });
    // });

    // 导出项目
    $('#getExeclTxt').on('click',function () {
        let a = document.createElement('a');
        a.href = '/manage/projectDetails/export_busInfo.do';
        a.click();
    });

    // addYouXiu  --ok
    function addYouXiu( ID, DOM ) {
        $.ajax({
            url: '/manage/projectDetails/set_excellent_works.do',
            type: 'post',
            data: {
                projectnoList : ID
            },
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success: function (data) {
                if (data.status == 0) {
                    spop_ok( data.msg, function () {
                        youXiuCss( DOM, true );
                    } );
                }else if( data.status == 10 ){
                    spop_waring( data.msg, function () {}, outLogin )
                }else{
                    spop_waring( data.msg );
                }
            }
        });
    }
    // removeYouXiu --ok
    function removeYouXiu( ID, DOM ) {
        $.ajax({
            url: '/manage/projectDetails/del_excellent_works.do',
            type: 'post',
            data: {
                projectnoList : ID
            },
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success: function (data) {
                if (data.status == 0) {
                    spop_ok( data.msg, function () {
                        youXiuCss( DOM, false )
                    } );
                }else if( data.status == 10 ){
                    spop_waring( data.msg, function () {}, outLogin )
                }else{
                    spop_waring( data.msg );
                }
            }
        });
    }
    // 优秀项目切换 --ok
    function youXiuCss( DOM, OFF ) {
        if( OFF ){
            DOM.find('.setThisBtn').children('i').first().addClass('active');
            DOM.attr('data-youxiu_status', Number(OFF)  );
        }else{
            DOM.find('.setThisBtn').children('i').first().removeClass('active');
            DOM.attr('data-youxiu_status', Number(OFF)  );
        }
    }

    /********************************************/

    // 多选框控制
    $('#allChecked-OFF').on('click',function(){
        let OFF = $(this).is(':checked');
        off(OFF);
    });

    // 每个单选框的监听 --ok
    $('#table-tbody').on('change','input[type="checkbox"]',function(){

        let onOFF = $('#allChecked-OFF');// 总开关
        let thisOFF = $('#table-tbody').find('input[type="checkbox"]');// 单开关
        let arr = [];// 可用的按钮数组

        for(let i=0; i<thisOFF.length; i++){
            arr.push(thisOFF.eq(i).prop('checked'));
        }

        // 全true 输出true
        let allTRUE = arr.every(function(item,key,array){
            return item == true;
        });
        allTRUE ? onOFF.prop('checked',true) : onOFF.prop('checked',false);
    });

    // 所有单选框的控制  --ok
    function off( boolean ) {
        $('#allChecked-OFF').prop('checked',boolean);
        let aOff_Checkbox = $('#table-tbody').find('input[type="checkbox"]');
        for(let i=0; i<aOff_Checkbox.length; i++){
            aOff_Checkbox.eq(i).prop('checked',boolean);
        }
    }

    // 获取选中 用户列表
    function checked_TRUE() {
        let inputList = $('#table-tbody').find('input[type="checkbox"]');
        let oUserInfo = {
            thisID : [],
            thisDOM : []
        };

        // 获取所有选中 checked
        for(let i=0; i<inputList.length; i++){
            // 判断是否选中状态
            if(inputList.eq(i).is(":checked")){
                oUserInfo.thisID.push( inputList.eq(i).parents('tr').attr('data-id') );// 获取ID
                oUserInfo.thisDOM.push( inputList.eq(i).parents('tr') );
            }
        }

        if( oUserInfo.thisID.length ){
            return oUserInfo;
        }else{
            return false
        }
    }

});